<template>
  <n-select
    v-bind="props"
    :options="options"
    :loading="loading"
    :placeholder="placeholder"
    @update:value="handleUpdate"
    @search="handleSearch"
    @clear="handleSearch"
  />
</template>

<script lang="ts">
  import { defineComponent, reactive, toRefs } from 'vue'
  import { NSelect } from 'naive-ui'
  import { useStore } from '@/store'
  import { SelectBaseOption } from 'naive-ui/es/select/src/interface'

  export default defineComponent({
    name: 'XChangeShop',
    components: {
      NSelect
    },
    props: {
      ...NSelect.props,
      placeholder: {
        type: String,
        default: '查询选择店铺'
      },
      filterable: {
        type: Boolean,
        default: true
      },
      clearable: {
        type: Boolean,
        default: true
      },
      remote: {
        type: Boolean,
        default: true
      }
    },
    emits: ['update'],
    setup($props, { emit }) {
      const $store = useStore()
      const $state = reactive({
        props: toRefs($props) || {},
        loading: false,
        options: [],
        formData: {
          storeId: null,
          storeName: null
        }
      })

      const handleSearch = (val: string) => {
        if (/^\d+$/gi.test(val)) {
          $state.formData = {
            storeId: +val,
            storeName: null
          }
        } else {
          $state.formData = {
            storeId: null,
            storeName: val || null
          }
        }
        getShopList()
      }

      const getShopList = () => {
        const params = {
          ...$state.formData,
          pageNum: 1,
          pageSize: 20
        }
        $store.dispatch('shop/getShopList', params).then((res) => {
          //
          const list = res.data || []
          $state.options = list.map((item: any) => {
            // 和气saas只有appletName，没有storeName
            return {
              ...item,
              label: `${item.label || item.appletName || '-'}（StoreId：${item.storeId}）`
            }
          })
        })
      }
      getShopList()

      function handleUpdate(value: number, option: SelectBaseOption) {
        emit('update', option)
      }

      return {
        ...toRefs($state),
        handleSearch,
        handleUpdate
      }
    }
  })
</script>

<style></style>
